<?php
class Customer_Service_CustomerBalance
{
	 
	public function __construct($options){
		 
	}
	
	/*
	*
	*正常帐户扣款/入款 或者HOLD
	*@return 0:失败;1:成功;
	*/
	
	public static function procBalanceTransaction($customerId,$options){
		$customerBalance = new Customer_Model_CustomerBalance();
		$dbAdapter = $customerBalance->getAdapter();
		$dbAdapter->beginTransaction(); 
		try{
			$result = self::procBalance($customerId,$options);
			 
			if($result==='2'){
				$dbAdapter->rollback();			 
				return false;
			}
			 $dbAdapter->commit();
			
			 return $result;
		}catch(Exception $e){
	    	$dbAdapter->rollback();
			 
	    	return false;
	    }	
		
	}
	/*
	*
	*正常帐户扣款/入款 或者HOLD
	*@return 0:失败;1:成功;2:异常
	*/
	
	public static function procBalance($customerId,$options){
		
		if(!$customerId) return false;
		$paymentClass = $options['cbhClass'];//订单扣款类型 0:正常扣款/入款;1:冻结扣款/入款,2:订单回退--冻结扣款回退
		$refId = $options['refCode']; //参考记录ID 如订单号，产品号, ASN 号
		$appType = $options['appType']; //入账:1充值,2退款;借出:3:SKU,4:item,5:plant
		$cbhType = $options['cbhType']; //-1:扣款;1:充值
		$iniValue = $options['vale']; //金额
		$currencyCode = $options['currencyCode']; //币种
		$rate = @$options['rate']; //币种汇率
		$note = @$options['note']; //备注
		$opId = @$options['userId']; //后台操作人员ID/0系统操作/-1客户操作
		$cbharrive = @$options['cbharrive']; //到帐日期
		$cbharrive = $cbharrive == '' ? date('Y-m-d H:i:s'):$cbharrive;
		if(!$opId){
			$opId ='-1';	
		}
		$orgValue = $iniValue*$cbhType;
		$customerBalance = new Customer_Model_CustomerBalance();
		 
		$now = date('Y-m-d H:i:s');
		$balance = $customerBalance->lockForUpdate($customerId);
		
		$valueRate = Common_Service_Currency::changeCurrency($iniValue,$currencyCode,$balance['currency_code'],$rate);
		$value = $valueRate['value']*$cbhType;
		$currentValue = $balance['cb_value']+$value;
		
		if($currentValue<0){//余额小于支付金额
			return false;
		}

		$balanceLog = array('customer_id'=>$customerId,
											'cbh_base_value'=>$value,
											'cbh_value'=>$orgValue,
											'currency_rate'=>$valueRate['rate'],
											'currency_code'=>$currencyCode,
											//'ba_id'=>$paymentMethod['ba_id'],
											'cbh_note'=>$note,
											'cbh_type'=>$cbhType,
											'cbh_op_type'=>$appType,
											'cbh_class'=>$paymentClass,
											'cbh_refer_id'=>$refId,
											'user_id'=>$opId,
											'cbh_current_value'=>$currentValue ,
											'cbh_arrive_time'=>$cbharrive,
											'cbh_add_time'=>$now
											);
	 									
		$cbhObj = new Customer_Model_CustomerBalanceHistory();
		$cbhObj->add($balanceLog);											
		$balanceUpdate = array('cb_value'=>$currentValue,'cb_last_update'=>$now);
		if($paymentClass=='1')
			$balanceUpdate['cb_hold_value'] = $balance['cb_hold_value'] - $value;
		$customerBalance->update($balanceUpdate,$customerId);//unlock balance
		 
		 return true;					
	}
	
	/*
	*
	*release balance Value
	*对同一类型同一产品/订单多个扣费解冻
	*/
	
	public static function release($customerId,$refCode,$appType){
		
		if(!$customerId) return false;		
		if(!$refCode) return false;
		$now = date('Y-m-d H:i:s');
		$result['ask'] = "Success";
		$customerBalance = new Customer_Model_CustomerBalance();
			$cbhObj = new Customer_Model_CustomerBalanceHistory();
			$cbhRows = $cbhObj->getHold($customerId,$refCode,$appType);
			
			
			$balance = $customerBalance->lockForUpdate($customerId);
			$balanceHold = $balance['cb_hold_value'];
			$returnVale = 0;
			foreach($cbhRows as $cbhRow){
			
					$valueRate = Common_Service_Currency::changeCurrency($cbhRow['cbh_value'],$cbhRow['currency_code'],$balance['currency_code']);
					$value = $valueRate['value'];
					$currentValue = $balance['cb_value']-$value;
					$note = "release $refCode."; 
					$balanceHold = $balanceHold + $valueRate['value'];
					$returnVale += $valueRate['value'];
					if($balanceHold < 0){					
						$result['ask'] = "Error";
						$result['message'] = $note ."on hold money less than release!";	
						return $result;						
					} 
					
					 
					
					$customerBalanceHistory = array('cbh_class'=>2);
					$cbhObj->update($customerBalanceHistory,$cbhRow['cbh_id']);		//TODO unlock balance history
			}
			
			$balanceUpdate = array('cb_value'=>$balance['cb_value']-$returnVale,'cb_hold_value'=>$balance['cb_hold_value']+$returnVale,'cb_last_update'=>$now); 							
			$customerBalance->update($balanceUpdate,$customerId);//unlock balance
			return $result;
												
	}
	 
	
	
	/**
	* 获取用户Balance信息
	* @param  $customerId
	* @return array 
	*/
	public static function getByCustomer($customerId){
		$customerBalance = new Customer_Model_CustomerBalance();
		return $customerBalance->getByCustomer($customerId);
	}
	
	
	
	/**
	* 获取用户Balance Detail信息
	* @param  $options
	* @return array 
	*/
	public static function getByComdation($options,$type='*'){
	 
		if(!isset($options['customer_id'])) return;
		//时间处理
		if(!isset($options['startTime'])){
			$options['startTime'] = date('Y-m-d',strtotime("-1 month"))." 00:00:00"; 
		}else{
			$options['startTime'] = date('Y-m-d',strtotime("{$options['startTime']}"))." 00:00:00"; 
		}
		//时间处理
		if(!isset($options['endTime'])){
			$options['endTime'] = date('Y-m-d')." 23:59:59"; 
		}else{
			$options['endTime'] = date('Y-m-d',strtotime("{$options['endTime']}"))." 23:59:59"; 
		}	
		
		$start = 0;
		if($type!='*'){
			$type = "count(*) as count";
		}else{
			$type = "*";
			
			$start =($options['page'] -1)*$options['pageSize'];			
			
		}
		 
		
		$customerBalance = new Customer_Model_CustomerBalanceHistory();
		return $customerBalance->getByComdation($options['customer_id'],$options['startTime'],$options['endTime'],$start,$options['pageSize'],$type)->toArray();
	}

}